import 'package:fish_redux/fish_redux.dart';
import 'action.dart';
import 'state.dart';
import '../../../../app_files.dart';

Effect<OrderDetailListViewState> buildEffect() {
  return combineEffects(<Object, Effect<OrderDetailListViewState>>{
    Lifecycle.initState: _initState,
    Lifecycle.dispose: _dispose,
  });
}

void _dispose(Action action, Context<OrderDetailListViewState> ctx) {
  bus.off('bindSuccess');
}

void _initState(Action action, Context<OrderDetailListViewState> ctx) async {
  ResultData configRes = await CommonNetWork.getSystemConfig();
  if (configRes.success) {
    List data = configRes.data;
    Map config = data.first;
    List value = config['ConfigValue'];
    value.forEach((element) {
      if (element['Key'] == 'mobile') {
        ctx.state.consumerPhone = element['Value'];
      }
    });
  }

  ResultData res = await CommonNetWork.orderPayType();
  if (res.success) {
    List data = res.data;
    List item = data
        .map((e) => OrderPayTypeModel(
              typeName: CommonUtils.checkNullToString(e['TypeName']),
              typeID: CommonUtils.checkNullToString(e['TypeId']),
            ))
        .toList();
    ctx.dispatch(OrderDetailListViewActionCreator.onGetData(item));
  } else {
    await CommonUtils.showAlertView(ctx.context, res.desc);
    Navigator.pop(ctx.context);
  }

  ResultData statusRes =
      await CommonNetWork.getBindBluetoothStatus(ctx.state.model.accountNo);
  if (statusRes.success) {
    ctx.state.bluetoothNo = statusRes.data;
    ctx.dispatch(OrderDetailListViewActionCreator.onAction());
  }

  bus.on('bindSuccess', (arg) {
    ctx.state.bluetoothNo = arg;
    ctx.dispatch(OrderDetailListViewActionCreator.onAction());
  });
}
